package com.pijunn.register

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils;
import org.codehaus.groovy.grails.plugins.springsecurity.ui.RegistrationCode;

import com.pijunn.common.Address;
import com.pijunn.users.AppUser;

class RegisterController extends grails.plugins.springsecurity.ui.RegisterController {
	
	/** dependency injection for the captcha service */
	def jcaptchaService
	
	/** dependency injection for the profile service */
	def profileService


	def index = {
			[addressInstance: new Address()]
	}
	
	def register = {
		
		if (request.method == 'POST') {
			def u = new AppUser(params)
			u.createTime = new Date()
			def hasErrors = false
			
			if (u.password != params.confirmPassword) {
				u.errors.rejectValue("password", "appUser.password.mismatch")
				hasErrors = true
			}
			if (u.contactEMail != params.confirmEMail) {
				u.errors.rejectValue("contactEMail", "appUser.email.mismatch")
				hasErrors = true
			}
			if (!jcaptchaService.validateResponse("imageCaptcha", session.id, params.captchaResponse)) {
				u.errors.rejectValue("captchaResponse", "appUser.captcha.invalid")
				hasErrors = true
			}
			if (!hasErrors && u.validate()) {
				try {
					profileService.createUser(u)
				}
				catch(Exception e) {
					log(e)
					render(view:'index', model:[appUserInstance: u, addressInstance: new Address(), confirmPassword: params.confirmPassword, confirmEMail: params.confirmEMail])
				}
				
				flash.message = message(code: 'appUser.created.message')
				render(view: "registrationComplete", model:[user: u])
				return
			}

			render(view:'index', model:[appUserInstance: u, addressInstance: new Address(), confirmPassword: params.confirmPassword, confirmEMail: params.confirmEMail])
		}
		else {
			[addressInstance: new Address()]
		}
	}

	def forgotPassword = {
		
		if (!request.post) {
			// show the form
			return
		}

		String username = params.username
		if (!username) {
			flash.error = message(code: 'spring.security.ui.forgotPassword.username.missing')
			redirect action: 'forgotPassword'
			return
		}

		String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName
		def user = lookupUserClass().findWhere((usernameFieldName): username)
		if (!user) {
			flash.error = message(code: 'spring.security.ui.forgotPassword.user.notFound')
			redirect action: 'forgotPassword'
			return
		}

		def registrationCode = new RegistrationCode(username: user."$usernameFieldName")
		registrationCode.save(flush: true)

		String url = generateLink('resetPassword', [t: registrationCode.token])

		def conf = SpringSecurityUtils.securityConfig
		def body = conf.ui.forgotPassword.emailBody
		if (body.contains('$')) {
			body = evaluate(body, [user: user, url: url])
		}
		mailService.sendMail {
			to user.contactEMail
			from conf.ui.forgotPassword.emailFrom
			subject conf.ui.forgotPassword.emailSubject
			html body.toString()
		}

		[emailSent: true]
	}

}
